import { AfterViewInit, Component, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzTableQueryParams } from 'ng-zorro-antd/table';
import { Consts } from 'src/app/consts/consts';
import { ClientQueryParam } from 'src/app/models/param/client-query.param';
import { ClientDto } from 'src/app/models/sys/client.dto';
import { ApiService } from 'src/app/services/api.service';
import { ContentHeaderService } from 'src/app/services/content-header.service';

const CLIENT_ID = 'clientId';
const CLIENT_NAME = 'clientName';

@Component({
  selector: 'app-permission',
  templateUrl: './permission.component.html',
  styleUrls: ['./permission.component.less']
})
export class PermissionComponent implements OnInit, AfterViewInit {
  // Search clients fields
  clientId?: string;
  clientName?: string;
  searchForm!: UntypedFormGroup;
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  submitted = false;
  
  // client list
  clients: ClientDto[] = [];

  constructor(private _api: ApiService,
    private _fb: UntypedFormBuilder,
    private _message: NzMessageService,
    private _router: Router,
    private _contentHeader: ContentHeaderService) { }

  ngAfterViewInit(): void {
    setTimeout(() => {
      this._contentHeader.header.next('权限管理');
    });
  }

  ngOnInit(): void {
    this.createSearchForm();
    this.onSearch();
  }

  createSearchForm() {
    this.searchForm = this._fb.group({});
    this.searchForm.addControl(CLIENT_ID, new UntypedFormControl('', [Validators.maxLength(20)]));
    this.searchForm.addControl(CLIENT_NAME, new UntypedFormControl('', [Validators.maxLength(20)]));
  }

  onSearch() {
    const param = new ClientQueryParam();
    param.clientId = this.clientId;
    param.clientName = this.clientName;

    this._api.getClientList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.clients = resp.data;
      }
    });
  }

  onReset() {
    this.clientId = undefined;
    this.clientName = undefined;
  }

  onPageParamChange(params: NzTableQueryParams) {
    this.pageIndex = params.pageIndex;
    this.pageSize = params.pageSize;
    this.onSearch();
  }

  onEditRole(clientId: string) {
    console.log(`ready to navigate to permission-detail with ${clientId} of index 0`);
    this._router.navigate(["/permission-detail"], { queryParams: { clientId: clientId, index: 0 } });
  }

  onEditPermission(clientId: string) {
    console.log(`ready to navigate to permission-detail with ${clientId} of index 1`);
    this._router.navigate(["/permission-detail"], { queryParams: { clientId: clientId, index: 1 } });
  }

  get fm() {
    return this.searchForm.controls;
  }
}
